<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryRef"
            :inline="true"
            label-width="auto"
            v-show="showSearch"
        >
            <el-row>
                <el-form-item label="生产单编码" prop="produceNo">
                    <el-input
                        v-model.trim="queryParams.produceNo"
                        style="width: 180px"
                        placeholder="请输入生产单编码"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="书刊编码" prop="bookCode">
                    <el-input
                        v-model.trim="queryParams.bookCode"
                        style="width: 180px"
                        placeholder="请输入书刊编码"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="出版编号" prop="pubNo">
                    <el-input
                        v-model.trim="queryParams.pubNo"
                        style="width: 180px"
                        placeholder="请输入出版编号"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <div class="operation">
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    <el-button @click="advanced = !advanced">
                        <a style="color: #448ef7">
                            <el-icon v-if="advanced">
                                <ArrowUpBold />
                            </el-icon>
                            <el-icon v-else>
                                <ArrowDownBold />
                            </el-icon>
                        </a>
                    </el-button>
                </div>
            </el-row>
            <el-row v-if="advanced">
                <el-form-item label="书刊名称" prop="bookName">
                    <el-input
                        v-model.trim="queryParams.bookName"
                        style="width: 180px"
                        placeholder="请输入书刊名称"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="下单日期" prop="submitDate">
                    <el-date-picker
                        style="width: 180px"
                        v-model="queryParams.submitDate"
                        value-format="YYYY-MM-DD "
                        type="date"
                        placeholder="请选择日期"
                    />
                </el-form-item>
                <el-form-item label="定价" prop="fixPrice">
                    <el-input
                        v-model.trim="queryParams.fixPrice"
                        style="width: 180px"
                        placeholder="请输入定价"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="书号" prop="bookNo">
                    <el-input
                        v-model.trim="queryParams.bookNo"
                        style="width: 180px"
                        placeholder="请输入书号"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="纸型" prop="paperType">
                    <el-input
                        v-model.trim="queryParams.paperType"
                        style="width: 180px"
                        placeholder="请输入纸型"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="定量" prop="weight">
                    <el-input
                        v-model.trim="queryParams.weight"
                        style="width: 180px"
                        placeholder="请输入定量"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <!-- <el-form-item label="内文承印长" prop="orderName">
                    <el-input v-model.trim="queryParams.orderName" style="width: 180px;" placeholder="请输入内文承印长"
                        @keyup.enter="handleQuery" />
                </el-form-item> -->
                <el-form-item label="客户名称" prop="customerName">
                    <el-input
                        v-model.trim="queryParams.customerName"
                        style="width: 180px"
                        placeholder="请输入客户名称"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="科目" prop="subjectType">
                    <el-select
                        style="width: 180px"
                        v-model="queryParams.subjectType"
                        placeholder="请选择科目"
                    >
                        <el-option
                            v-for="item in ems_workshop_subject_type"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select
                        style="width: 180px"
                        filterable
                        v-model="queryParams.status"
                        placeholder="请选择状态"
                    >
                        <el-option
                            v-for="item in ems_order_status"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
            </el-row>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    :disabled="multiple"
                    plain
                    icon="Printer"
                    @click="handlePrintList"
                >
                    打印
                </el-button>
            </el-col>
            <right-toolbar
                v-model:showSearch="showSearch"
                @queryTable="getList"
                :columns="columns"
            ></right-toolbar>
        </el-row>
        <div>
            <el-table
                height="65vh"
                @selection-change="handleSelectionChange"
                v-loading="loading"
                border
                :data="dataList"
            >
                <el-table-column
                    type="selection"
                    :selectable="selectable"
                    align="center"
                    width="40"
                />
                <el-table-column label="序号" width="60" type="index" align="center" />
                <el-table-column
                    label="状态"
                    min-width="100"
                    align="center"
                    :show-overflow-tooltip="true"
                    prop="status"
                    v-if="columns[0].visible"
                >
                    <template v-slot="{ row }">
                        <dict-tag :options="ems_order_status" :value="row.status" />
                    </template>
                </el-table-column>
                <el-table-column
                    label="数据状态"
                    min-width="100"
                    align="center"
                    :show-overflow-tooltip="true"
                    prop="isSuspend"
                    v-if="columns[0].visible"
                >
                    <template v-slot="{ row }">
                        <el-tag
                            :type="row.isSuspend == 1 ? 'error' : 'success'"
                            effect="dark"
                            round
                        >
                            {{ row.isSuspend == 1 ? '暂停' : '正常' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    label="生产单编码"
                    min-width="160"
                    align="center"
                    :show-overflow-tooltip="true"
                    prop="orderNo"
                    v-if="columns[1].visible"
                >
                    <template v-slot="{ row }">
                        <el-button type="primary" @click="handleView(row)" text>
                            {{ row.produceNo }}
                        </el-button>
                    </template>
                </el-table-column>
                <!-- <el-table-column
          label="新/旧版"
          align="center"
          min-width="150"
          :show-overflow-tooltip="true"
          prop="isNew"
          v-if="columns[2].visible"
        >
          <template v-slot="{ row }">
            <dict-tag :options="ems_produce_is_new" :value="row.isNew" />
          </template>
        </el-table-column> -->
                <el-table-column
                    label="出版编号"
                    min-width="120"
                    align="center"
                    :show-overflow-tooltip="true"
                    prop="pubNo"
                    v-if="columns[3].visible"
                ></el-table-column>
                <el-table-column
                    label="下单日期"
                    min-width="120"
                    align="center"
                    :show-overflow-tooltip="true"
                    prop="submitDate"
                    v-if="columns[4].visible"
                >
                    <template v-slot="{ row }">
                        {{ row.submitDate?.split('T')[0] ?? '' }}
                    </template>
                </el-table-column>
                <el-table-column
                    label="交货日期"
                    min-width="120"
                    align="center"
                    :show-overflow-tooltip="true"
                    prop="deliverDate"
                    v-if="columns[5].visible"
                >
                    <template v-slot="{ row }">
                        {{ row.deliverDate?.split('T')[0] ?? '' }}
                    </template>
                </el-table-column>
                <el-table-column
                    label="加急交货日期"
                    min-width="120"
                    align="center"
                    :show-overflow-tooltip="true"
                    prop="urgentDate"
                    v-if="columns[6].visible"
                >
                    <template v-slot="{ row }">
                        {{ parseTime(row.urgentDate) }}
                    </template>
                </el-table-column>

                <el-table-column
                    label="操作"
                    align="center"
                    width="150"
                    fixed="right"
                    class-name="small-padding fixed-width"
                >
                    <template #default="scope">
                        <el-tooltip content="修改" placement="top" v-if="scope.row.status == 1">
                            <el-button
                                link
                                type="primary"
                                icon="Edit"
                                @click="handleUpdate(scope.row)"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top" v-if="scope.row.status == 1">
                            <el-button
                                link
                                type="primary"
                                icon="Delete"
                                @click="handleDelete(scope.row)"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip content="复制新增" placement="top">
                            <el-button
                                link
                                type="primary"
                                icon="CopyDocument"
                                @click="handleCopy(scope.row)"
                            ></el-button>
                        </el-tooltip>
                        <!-- <el-tooltip content="打印" placement="top">
                            <el-button
                                link
                                type="primary"
                                icon="Printer"
                                @click="handlePrint(scope.row)"
                            ></el-button>
                        </el-tooltip> -->
                        <el-button
                            link
                            type="primary"
                            v-if="scope.row.status == 1"
                            @click="handleSubmit(scope.row)"
                        >
                            提交
                        </el-button>
                        <el-button
                            link
                            type="primary"
                            v-if="
                                scope.row.status == 2 ||
                                scope.row.status == 3 ||
                                scope.row.status == 4
                            "
                            @click="handleInvalidate(scope.row)"
                        >
                            作废
                        </el-button>
                        <el-button
                            link
                            type="primary"
                            v-if="
                                scope.row.status == 2 ||
                                scope.row.status == 3 ||
                                scope.row.status == 4
                            "
                            @click="handleUrgentDate(scope.row)"
                        >
                            加急
                        </el-button>
                        <el-button
                            link
                            type="primary"
                            v-if="scope.row.status == 2 && scope.row.makeStatus == 1"
                            @click="handleBack(scope.row)"
                        >
                            撤回
                        </el-button>
                        <el-button
                            link
                            type="primary"
                            v-if="scope.row.status > 4 && scope.row.isSuspend != 1"
                            @click="handleSuspend(scope.row)"
                        >
                            暂停
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination
                v-show="total > 0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
            />
        </div>
        <!-- 用户导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <el-upload
                ref="uploadRef"
                :limit="1"
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag
            >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <div class="el-upload__tip">
                            <el-checkbox v-model="upload.updateSupport" />
                            是否更新已经存在的用户数据
                        </div>
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link
                            type="primary"
                            :underline="false"
                            style="font-size: 12px; vertical-align: baseline"
                            @click="importTemplate"
                        >
                            下载模板
                        </el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog
            title="生产单加急"
            v-model="urgentOpen"
            width="35%"
            append-to-body
            @close="closed"
        >
            <el-form :model="queryDate" ref="queryDateForm" :rules="rules" :inline="true">
                <el-form-item label="加急交货日期" prop="urgentDate">
                    <el-date-picker
                        style="width: 100%"
                        v-model="queryDate.urgentDate"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        date-format="MMM DD, YYYY"
                        time-format="HH:mm"
                        type="datetime"
                        placeholder="请选择时间"
                    />
                </el-form-item>
            </el-form>
            <div class="footer">
                <el-button type="primary" @click="submitFill">确定</el-button>
                <el-button @click="urgentOpen = false">取消</el-button>
            </div>
        </el-dialog>
        <printFM
            :visible="printOpen"
            :printList="printList"
            @cancel="
                () => {
                    printOpen = false
                    printList = []
                    selectRow = []
                }
            "
            :id="mainId"
        ></printFM>
    </div>
</template>

<script setup name="order">
// 编号改成序列号 纸张编号 印刷编号
import { downLoad, parseTime } from '@/utils/ruoyi'
import useTagsViewStore from '@/store/modules/tagsView'
const tagsViewStore = useTagsViewStore()
import {
    getProduceOrderList,
    delProduceById,
    updateUrgentDate,
    updateStatus,
    updatesuspend,
} from '@/api/production/cover'
import printFM from './printFM.vue'
const { proxy } = getCurrentInstance()
const loading = ref(true)
const dataList = ref([])
const showSearch = ref(true)
const total = ref(0)
const advanced = ref(false)
const urgentOpen = ref(false)
const router = useRouter()
const mainId = ref('')
const selectId = ref(undefined)
const queryDateForm = ref(null)
const printOpen = ref(false)
const multiple = ref(true)
const selectRow = ref([])
const printList = ref([])
import { getToken } from '@/utils/auth'
/*** 用户导入参数 */
const upload = reactive({
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: 'Bearer ' + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + '/mes/user/importMesUserInfo',
})
// 列显隐信息
const columns = ref([
    { key: 0, label: `状态`, visible: true },
    { key: 1, label: `生产单编码`, visible: true },
    { key: 2, label: `新/旧版`, visible: true },
    { key: 3, label: `出版编号`, visible: true },
    { key: 4, label: `下单日期`, visible: true },
    { key: 5, label: `交货日期`, visible: true },
    { key: 6, label: `加急交货日期`, visible: true },
])

const data = reactive({
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: 1,
        orderName: undefined,
        orderNo: undefined,
    },
    queryDate: {
        urgentDate: undefined,
    },
    rules: {
        urgentDate: [{ required: true, message: '加急交货日期不能为空', trigger: 'blur' }],
    },
})
const { queryParams, queryDate, rules } = toRefs(data)

const { ems_workshop_subject_type, ems_order_status, ems_produce_is_new } = proxy.useDict(
    'ems_order_status',
    'ems_workshop_subject_type',
    'ems_produce_is_new'
)

const getList = () => {
    loading.value = true
    getProduceOrderList(queryParams.value)
        .then(res => {
            loading.value = false
            dataList.value = res.rows
            // if (res.rows.length > 0) {
            //     mainId.value = res.rows[0].produceId
            // }
            total.value = res.total
        })
        .catch(err => {
            loading.value = false
        })
}
// 新增
const handleAdd = () => {
    tagsViewStore.delView({ name: 'coverDetails', path: '/production/cover/coverDetails' })
    router.push('/production/cover/coverDetails')
}
// 编辑
const handleUpdate = row => {
    router.push({
        path: '/production/cover/coverDetails',
        query: {
            id: row.produceId,
        },
    })
}
// 查看
const handleView = row => {
    router.push({
        path: '/production/cover/coverDetails',
        query: {
            id: row.produceId,
            info: true,
        },
    })
}
// 复制新增
const handleCopy = row => {
    router.push({
        path: '/production/cover/coverDetails',
        query: {
            id: row.produceId,
            copy: true,
        },
    })
}
// 打印
const handlePrint = row => {
    mainId.value = row.produceId
    printOpen.value = true
}
// 多选打印
const handlePrintList = () => {
    printOpen.value = true
    printList.value = selectRow.value
}

const handleSelectionChange = row => {
    selectRow.value = row
    // selectBookNo.value = row.map(item => item.produceId)
    multiple.value = !row.length
}
// 提交
const handleSubmit = row => {
    proxy.$modal
        .confirm('是否确认提交"' + row.produceNo + '"的生产单？')
        .then(function () {
            return updateStatus({ status: 2, pid: row.produceId })
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess('提交成功')
        })
        .catch(() => {})
}
// 撤回
const handleBack = row => {
    proxy.$modal
        .confirm('是否确认撤回"' + row.produceNo + '"的生产单？')
        .then(function () {
            return updateStatus({ status: 1, pid: row.produceId })
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess('撤回成功')
        })
        .catch(() => {})
}
// 暂停
const handleSuspend = row => {
    proxy.$modal
        .confirm('是否确认暂停"' + row.produceNo + '"的生产单？')
        .then(function () {
            return updatesuspend({ isSuspend: 1, pid: row.produceId })
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess('暂停成功')
        })
        .catch(() => {})
}
// 作废
const handleInvalidate = row => {
    proxy.$modal
        .confirm('是否确认作废"' + row.produceNo + '"的生产单？')
        .then(function () {
            return updateStatus({ status: 0, pid: row.produceId })
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess('作废成功')
        })
        .catch(() => {})
}
// 加急
const handleUrgentDate = row => {
    selectId.value = row.produceId
    urgentOpen.value = true
}
const closed = () => {
    proxy.resetForm('queryDateForm')
}
const submitFill = row => {
    queryDateForm.value.validate(valid => {
        if (valid) {
            updateUrgentDate({ ...queryDate.value, pid: selectId.value }).then(res => {
                urgentOpen.value = false
                proxy.$modal.msgSuccess('加急成功')
                getList()
            })
        }
    })
}
// 搜索
const handleQuery = () => {
    queryParams.value.pageNum = 1
    getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
    proxy.resetForm('queryRef')
    handleQuery()
}
/** 删除按钮操作 */
function handleDelete(row) {
    proxy.$modal
        .confirm('是否确认删除"' + row.produceNo + '"生产单？')
        .then(function () {
            return delProduceById({ pid: row.produceId })
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
}
// 导出
const handleExport = () => {
    exportMesOrder(queryParams.value).then(res => {
        downLoad(res.msg, '订单列表')
    })
}

/** 下载模板操作 */
function importTemplate() {
    exportTemplate().then(res => {
        downLoad(res.msg, '人员模版')
    })
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false
    upload.isUploading = false
    proxy.$refs['uploadRef'].handleRemove(file)
    proxy.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
            response.msg +
            '</div>',
        '导入结果',
        { dangerouslyUseHTMLString: true }
    )
    getList()
}

/** 提交上传文件 */
function submitFileForm() {
    proxy.$refs['uploadRef'].submit()
}
getList()
// router.beforeEach((to, from, next) => {
//     if (to.path == "/basicInfo/personnel") {
//         getList()
//     }
//     next();
// });
</script>

<style lang="scss" scoped>
.operation {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-bottom: 18px;
}
</style>
